import axios from 'axios'
import '@/http/http'

// 封装post请求
export function requestByPost(url, params = {}) {
  return axios({
    url: url,
    method: 'post',
    data: params
  })
}

// 封装get请求
export function requestByGet(url, params = {}) {
  // 去除参数中为空的字段
  for (const key in params) {
    if (params[key] === null || params[key] === undefined || params[key] === '') {
      delete params[key]
    }
  }
  return axios({
    url: url,
    method: 'get',
    params: params
  })
}

// 封装put请求
export function requestByPut(url, params = {}) {
  return axios({
    url: url,
    method: 'put',
    data: params
  })
}

// 封装delete请求
export function requestByDelete(url, params = {}) {
  return axios({
    url: url,
    method: 'delete',
    params: params
  })
}

// 封装下载请求
export function requestDownfile(url, params = {}) {
  return axios({
    url: url,
    method: 'get',
    params: params,
    responseType: 'blob'
  })
}

// 老平台文件上传
export async function requestUploadFile(url, file, path) {
  let res = await axios({
    url: url, //获取阿里云文件上传配置地址
    method: 'post',
    data: {
      fileName: file.name,
      path: path
    }
  })
  if(res.code === 200) {
    let formData = new FormData()
    formData.append('key', res.data.dir + res.data.fileName) //存储在oss的文件路径
    formData.append('OSSAccessKeyId', res.data.accessid) //accessKeyId
    formData.append('policy', res.data.policy) //policy
    formData.append('Signature', res.data.signature) //签名
    formData.append('file', file) //如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
    formData.append('success_action_status', 200) //成功后返回的操作码
    await axios({
      url: res.data.host,
      method: 'post',
      data: formData,
      headers: {
        'Access-Control-Allow-Origin': '*'
      }
    })
  }
  return {
    src: res.data.host + '/' + res.data.dir + res.data.fileName,
    name: file.name
  }
}